using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace TmxLib
{
    public class TmxReader
    {
        public static TmxImage Parse(XmlDocument doc)
        {
            TmxHeader header = new TmxHeader();

            XmlElement elHeader = (XmlElement) doc.DocumentElement.SelectSingleNode("header");
            if (elHeader != null)
            {
                header.DefaultCultureName = elHeader == null ? null : elHeader.GetAttribute("defaultLanguage");
                string cultures = elHeader.GetAttribute("languages");
                header.Cultures = TmxLanguageCollection.Parse(cultures);
            }

            TmxItemCollection list = new TmxItemCollection();
            TmxImage ret = new TmxImage(header, list);

            string version = doc.DocumentElement.GetAttribute("version");
            ret.Version = version == null ? "1.1" : version;
            
            XmlNodeList nl = doc.SelectNodes("//body/tu");
            foreach (XmlElement tu in nl)
            {
                XmlElement elProp = (XmlElement)tu.SelectSingleNode("prop[@type='context']");
                if (elProp != null)
                {
                    string context = elProp.InnerText;
                    TmxItem tmxItem = new TmxItem(context);
                    XmlNodeList tuvList = tu.SelectNodes("tuv");
                    foreach (XmlElement tuv in tuvList)
                    {
                        string lang = tuv.GetAttribute("lang");
                        string @ref = tuv.GetAttribute("ref");
                        XmlElement elSeg = (XmlElement)tuv.SelectSingleNode("seg");
                        if (elSeg != null)
                        {
                            string value = elSeg.InnerText;
                            TmxItemValue iv = new TmxItemValue(lang, value);
                            if (@ref != null && @ref.Length > 0)
                                iv.Ref = @ref;

                            tmxItem.Values.Add(iv);

                        }
                    }

                    ret.Items.Add(tmxItem);
                }
            }

            if (header.Cultures.Count == 0)
            {
                header.Cultures.Add(new TmxLanguage(header.DefaultCultureName, true));
                string[] ll = ret.Items.GetLanguages();
                foreach(string l in ll)
                {
                    if (l != header.DefaultCultureName)
                        header.Cultures.Add(new TmxLanguage(l, false));
                }
            }

            return ret;
        }
    }
}
